﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.Services;
using PanasonicWarranty.Business;
using System.Web.UI.HtmlControls;
using Utils;
using System.Data;
namespace PanasonicWarranty.UI
{
    public partial class SynthesisWarrantyManagement : BasePageManageWarranty
    {
        protected override void OnInit(EventArgs e)
        {
            base.OnInit(e);
            pagingtop.PagingChange += new EventHandler(paging_PagingChange);
            pagingbottom.PagingChange += new EventHandler(paging_PagingChange);
        }

        void paging_PagingChange(object sender, EventArgs e)
        {
            pagingtop.CurrentPage = (sender as UserControl.ucPaging).CurrentPage;
            pagingbottom.CurrentPage = (sender as UserControl.ucPaging).CurrentPage;
            BindGridData();
        }

        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                txtSearchFromDate.Text = txtSearchToDate.Text = DateTime.Now.ToShortDateString();
                PageSize = Convert.ToInt32(tSortable_length.SelectedValue);
                pagingtop.CurrentPage = pagingbottom.CurrentPage = 1;
                pagingtop.PageSize = pagingbottom.PageSize = PageSize;
                pagingtop.PageDisplay = pagingbottom.PageDisplay = 6;
                BindDropDownData();
                //BindGridData();
            }
        }

        private void BindGridData()
        {
            try
            {
                if (!CheckSearch()) return;
                int currentPage = pagingtop.CurrentPage;
                int pageSize = pagingtop.PageSize;
                int totalRow = 0;
                string model = ddlSearchModel.SelectedValue;
                string productcode = txtSearchProductCode.Text.Trim();
                string phone = txtSearchPhone.Text.Trim();
                int? agencyid = ddlSearchAgency.SelectedValue == "" ? (int?)null : int.Parse(ddlSearchAgency.SelectedValue);
                string status = ddlSearchStatus.SelectedValue.ToNullIfNullOrEmpty();
                DateTime fromDate = Convert.ToDateTime(txtSearchFromDate.Text, DateTimeFormat);
                DateTime toDate = Convert.ToDateTime(txtSearchToDate.Text, DateTimeFormat).AddHours(24);
                grvData.DataSource = pa_WarrantyDetail.PagingDetailAndReject(currentPage, pageSize, ref totalRow, agencyid, model, productcode, phone, status, fromDate, toDate);
                pagingtop.TotalRecord = pagingbottom.TotalRecord = totalRow;
                pagingtop.Visible = pagingbottom.Visible = pagingtop.TotalPage > 1;
                grvData.DataBind();
                ltrInfo.Text = "Tổng cộng: " + totalRow;
            }
            catch (Exception ex)
            {
                HandleException(ex);
            }
        }

        private void BindDropDownData()
        {
            try
            {
                BindDropDownListData(ddlSearchModel, DB.pa_Models.ToList(), "ModelCode", "ModelCode", new ListItem(""));
                ddlSearchAgency.Items.Clear();
                bool isAdmin = IsRootAdmin();
                List<pa_Agency> list;
                if (isAdmin)
                    list = pa_Agency.GetAll();
                else
                    list = pa_Agency.GetAll(CurUser.AgencyID.Value);
                pa_Agency.TransformLevel(ref list);
                foreach (var item in list)
                {
                    ddlSearchAgency.Items.Add(new ListItem(item.AgencyName.ShowNameLevel(item.Level), item.AgencyID.ToString()));
                }
                if (isAdmin)
                    ddlSearchAgency.Items.Insert(0, new ListItem(""));
            }
            catch { }
        }

        protected void btnSearch_Click(object sender, EventArgs e)
        {
            pagingtop.PagingChange -= new EventHandler(paging_PagingChange);
            pagingbottom.PagingChange -= new EventHandler(paging_PagingChange);
            pagingtop.CurrentPage = pagingbottom.CurrentPage = 1;
            pagingtop.PagingChange += new EventHandler(paging_PagingChange);
            pagingbottom.PagingChange += new EventHandler(paging_PagingChange);
            BindGridData();
        }

        protected void tSortable_length_SelectedIndexChanged(object sender, EventArgs e)
        {
            try
            {
                PageSize = Convert.ToInt32(tSortable_length.SelectedValue);
                pagingtop.PageSize = pagingbottom.PageSize = PageSize;
                BindGridData();
            }
            catch { }
        }

        protected void btnSave_Click(object sender, EventArgs e)
        {
            try
            {
                Authorize(Role.Write);
                List<int> checkedID = new List<int>();
                foreach (GridViewRow item in grvWarrantyStatus.Rows)
                {
                    CheckBox chk = item.FindControl("chkChecked") as CheckBox;
                    if (chk != null)
                    {
                        if (chk.Checked)
                        {
                            HiddenField hdf = item.FindControl("hdfWarrantyStatusID") as HiddenField;
                            if (hdf != null)
                                checkedID.Add(Convert.ToInt32(hdf.Value));
                        }
                    }
                }
                pa_WarrantyStatusStruct.Insert(hdfID.Value, checkedID);
            }
            catch (Exception ex)
            {
                HandleException(ex);
            }
        }

        protected void lbtnAddNew_Click(object sender, EventArgs e)
        {
   
        }

        private bool CheckSearch()
        {
            try
            {
                if (string.IsNullOrWhiteSpace(txtSearchFromDate.Text))
                    throw new Exception("Bắt buộc chọn ngày bắt đầu tìm kiếm");
                if (string.IsNullOrWhiteSpace(txtSearchToDate.Text))
                    throw new Exception("Bắt buộc chọn ngày kết thúc tìm kiếm");
                DateTime fromDate = Convert.ToDateTime(txtSearchFromDate.Text, DateTimeFormat);
                DateTime toDate = Convert.ToDateTime(txtSearchToDate.Text, DateTimeFormat);
                if (toDate < fromDate)
                    throw new Exception("Ngày kết thúc không được nhỏ hơn ngày bắt đầu");
                if (fromDate.AddMonths(3) < toDate)
                    throw new Exception("Giới hạn khoảng tìm kiếm là 3 tháng");
                ltrCheckSearch.Text = "";
                return true;
            }
            catch (Exception e)
            {
                ltrCheckSearch.Text = e.Message;
                return false;
            }
            
        }

        protected void btnExport_Click(object sender, EventArgs e)
        {
            try
            {
                Authorize(Role.Export);
                if (!CheckSearch()) return;
                string model = ddlSearchModel.SelectedValue;
                string productcode = txtSearchProductCode.Text.Trim();
                string phone = txtSearchPhone.Text.Trim();
                int? agencyid = ddlSearchAgency.SelectedValue == "" ? (int?)null : int.Parse(ddlSearchAgency.SelectedValue);
                string status = ddlSearchStatus.SelectedValue.ToNullIfNullOrEmpty();
                DateTime fromDate = Convert.ToDateTime(txtSearchFromDate.Text, DateTimeFormat);
                DateTime toDate = Convert.ToDateTime(txtSearchToDate.Text, DateTimeFormat).AddHours(24);
                
                using (DataTable dt = pa_WarrantyDetail.GetDetailAndReject(agencyid, model, productcode, phone, status, fromDate, toDate))
                {
                    if (dt.Rows.Count > 0)
                    {
                        foreach (DataColumn col in dt.Columns)
                            col.Caption = pa_WarrantyDetail.GetCaption(col.ColumnName);
                        ExportToExcel(dt, "ExportTongHopThongTinBaoHanh.xlsx");
                    }
                    else
                    {
                        ShowMessageBox("Không có dữ liệu export");
                    }
                }
                InsertChangeLog("Export tổng hợp thông tin bảo hành");
            }
            catch (Exception ex)
            {
                HandleException(ex);
            }
        }
    }
}